import {View, Text, ScrollView} from '@tarojs/components'
import {useState, useEffect} from 'react';
import Taro, {useDidShow, useReachBottom} from '@tarojs/taro'
import {connect, useDispatch} from "react-redux";
import {AtSearchBar, AtModal, AtModalHeader, AtModalContent, AtModalAction, AtIcon, AtButton} from 'taro-ui'
import {
  Empty,
  PullToRefresh,
  Overlay,
  Loading,
  BackTop,
  ConfigProvider,
  Image,
  Tag
} from '@nutui/nutui-react-taro'
import {authLocation} from '../../utils'
import StationCard from '../../components/stationCard';
import mapIcon from '../../assets/mapIcon.png';
import './index.less'
import getBaseUrl from "../../service/baseUrl";

const base = getBaseUrl();
function Index(props) {
  const {
    dispatch,
    stationList,
    allActivities,
    myCoupons,
    chooseLocationInStore = {},
    searchValue,
    pageSize,
    total,
    loading
  } = props;
  // const access_token = Taro.getStorageSync('access_token');
  const isLogin = Taro.getStorageSync("isLogin");
  const action = useDispatch();
  const [isOpened, setOpen] = useState(false)
  const [chooseLocation, setLocation] = useState(chooseLocationInStore || {});
  const [scrollTop, setScrollTop] = useState(0);
  const [activityVisible, setActivityVisible] = useState(false);
  function search(val){
    dispatch({
      type: 'stations/load',
      payload: {
        searchText: val,
        pageNum: 1,
        pageSize: pageSize || 10,
      }
    })
  }
  const upDateLocal = (obj) => {
    dispatch({
      type: 'app/upState',
      payload: {
        chooseLocationInStore: obj
      }
    });
    dispatch({
      type: 'stations/init',
      payload: {
        action: action || undefined
      }
    });
  }
  useEffect(() => {
    setActivityVisible(!!allActivities.length && isLogin);
  }, [allActivities.length, isLogin]);
  useDidShow(() => {
    // const actionTwo = useDispatch();
    console.log('首页action', action);
    // console.log('首页actionTwo', actionTwo);
    console.log('首页')
    Taro.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        // var networkType = res.networkType
        console.log('首页的网络连接', res);
        if(res?.networkType && res.networkType !== 'none'){
          console.log('挖槽,首页有网');
          Taro.onNetworkStatusChange((RES) => {
            console.log('onNetworkStatusChange', RES);
            if (RES.isConnected) {
              //有网了以后，清空没网标识，进行页面刷新数据请求等...
              console.log('有网了,网是', RES.networkType);
              setTimeout(() => {
                // dispatch({
                //   type: 'stations/getAllActivity'
                // });
                if (action){
                  dispatch({
                    type: 'stations/init',
                    payload: {
                      action: action
                    }
                  });
                }
              }, 500)
              // Taro.reLaunch({
              //   url: '/pages/index/index'
              // })
              // _this.setData({
              //   netWorkType22: '有网了,网是' + res.networkType
              // })
            } else {
              //没网了，存个没网标识，然后需要请求的地方加个loading框
              console.log('没网了');
              // _this.setData({
              //   netWorkType22: '没网了'
              // })
            }

          })
        }
      }
    })
    Taro.setStorageSync('isScan', false);
    Taro.getPrivacySetting({
      success: res => {
        console.log('wx.getPrivacySetting', res) // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
        if (res.needAuthorization) {
          // 需要弹出隐私协议
          // this.setData({
          //   showPrivacy: true
          // })
        } else {
          // 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
          // wx.getUserProfile()
          // wx.chooseMedia()
          // wx.getClipboardData()
          // wx.startRecord()
        }
      },
      fail: () => {},
      complete: () => {}
    });
    const locationInfoStr = Taro.getStorageSync("chooseLocation") || "";
    if (locationInfoStr){
      setLocation(JSON.parse(locationInfoStr));
    } else {
      authLocation(upDateLocal);
      // 这里是获取下发权限地方，根据官方文档，可以根据  wx.getSetting() 的 withSubscriptions   这个参数获取用户是否打开订阅消息总开关。后面我们需要获取用户是否同意总是同意消息推送。所以这里要给它设置为true 。
      Taro.getSetting({
        withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
        success: function(res){
          // 调起授权界面弹窗
          if (res.subscriptionsSetting.mainSwitch) {  // 用户打开了订阅消息总开关
            if (res.subscriptionsSetting.itemSettings != null) {   // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
              let allowAll = true; // 默认全部授权
              for (let i in res.subscriptionsSetting.itemSettings){
                if (res.subscriptionsSetting.itemSettings[i] === 'reject') {
                  allowAll = false; // 有未授权的
                  break;
                }
              }
            }else {
              // 当用户没有点击 ’总是保持以上选择，不再询问‘  按钮。那每次执到这都会拉起授权弹窗
              Taro.showModal({
                title: '服务通知开通提醒',
                content:'请授权开通服务通知',
                showCancel: true,
                success: function (ress) {
                  if (ress.confirm) {
                    Taro.requestSubscribeMessage({   // 调起消息订阅界面
                      tmplIds: [
                        //   'PwwhxoYtybXHipy144Inr4A6OIXBvInOxx3ZpHr2bN8',
                        // 'twDx6apmVTru4MHSZNbXmwcdhbQpYs6z1rkpupGybNg',
                        // '9DKiuElZPygnp9FZ5lYqrt025di87aDYtD6tYIiL324'
                        'jUr1wPasDwRx9sOGdNOMSRmsjFC60ywC8ZOjXYGxfDQ',
                        'Y2zFgA_43XQ7FpRgru95P99HHYDf-QGXMjTZ3dihBpY',
                        '6ep4p9be_tI7DJFfKhMwXNm8_OUgO7DZVmWXAmmlrZI'
                      ],
                      success (sr) {
                        console.log('订阅消息 成功 ');
                        console.log(sr);
                      },
                      fail (er){
                        console.log("订阅消息 失败 ");
                        console.log(er);
                      }
                    })

                  }
                }
              })
            }

          }else {
            console.log('订阅消息未开启')
          }
        },
        fail: function(error){
          console.log(error);
        },
      })
    }
    // dispatch({
    //   type: 'stations/getAllActivity'
    // });
    if (action){
      dispatch({
        type: 'stations/init',
        payload: {
          action
        }
      });
    }
  })
  const {name: locationName = '', address: locationAddress = ''} = chooseLocation;
  const {name: locationNameStore = '', address: locationAddressStore = ''} = chooseLocationInStore;
  const nameFinally = locationName || locationNameStore;
  const addressFinally = locationAddress || locationAddressStore;
  const temStr = nameFinally + "-" + addressFinally;
  const WrapperStyle = {
    display: 'flex',
    height: '100%',
    alignItems: 'center',
    justifyContent: 'center'
  }
  useReachBottom(() => {
    wx.showToast({title: '正在加载...', icon: 'none'});
    if (pageSize >= total){
      // wx.showToast({title: '没有更多了~~', icon: 'none'});
      return;
    } else {
      // wx.showToast({title: '正在加载...', icon: 'none'});
      dispatch({
        type: 'stations/load',
        payload: {
          searchText: searchValue,
          pageNum: 1,
          pageSize: pageSize + 10,
        }
      })
    }
  });
  const allCouponsAvailable = [];
  if (allActivities.length){
    for (const d of allActivities){
      if (d.coupons && d.coupons.length){
        for (const l of d.coupons){
          allCouponsAvailable.push({
            ...l,
            activityId: d.activityId,
            activityType: d.activityType,
          })
        }
      }
    }
  }
  return (
      <View className='homeWrap'>
        <Overlay visible={activityVisible} closeOnOverlayClick={false}>
          <div style={WrapperStyle} />
        </Overlay>
        <View className='noticeBar'>
          <View className='searchLine'>
            <AtSearchBar
                showActionButton
                actionName={
                  <View className='mapBtn'>
                    <Image src={mapIcon} width='30' height='30' />
                    <Text>地图模式</Text>
                  </View>
                }
                placeholder='请输入充电站名或地址'
                value={searchValue}
                onChange={(e) => dispatch({type: 'stations/upState', payload: {searchValue: e}})}
                onActionClick={() => {
                  setTimeout(() => Taro.redirectTo({url: '/pages/index/chargeMap'}), 200)
                }}
                onConfirm={() => search(searchValue)}
                onClear={() => {
                  dispatch({type: 'stations/upState', payload: {searchValue: ''}})
                  setTimeout(() =>  search(''), 200)
                }}
                // onFocus={() => {
                //   setTimeout(() => {
                //     Taro.navigateTo({url: '/pages/index/search'})
                //   }, 100)
                // }}
            />
          </View>
          {/*<AtNoticebar single={false}>*/}
          {/*  <View>*/}
          {/*    <Text>*/}
          {/*      当前选择位置: {temStr}*/}
          {/*    </Text>*/}
          {/*    &nbsp;&nbsp;*/}
          {/*    <AtIcon*/}
          {/*      prefixClass='icon'*/}
          {/*      value='dingwei-'*/}
          {/*      size='28'*/}
          {/*      color='#00E39A'*/}
          {/*      onClick={() => {*/}
          {/*        dispatch({type: 'app/chooseLocation'});*/}
          {/*      }}*/}
          {/*    />*/}
          {/*  </View>*/}
          {/*</AtNoticebar>*/}
          <View className='moreAction'>
            <div
                className='card'
                onClick={() => {
                  if (!isLogin) {
                    setOpen(true);
                  } else {
                    dispatch({
                      type: 'stations/goChargingPage'
                    })
                  }
                }}
            >
              <div><i className='icon icon-car'/></div>
              <div>正在充电</div>
            </div>
            <div
                className='card'
                onClick={() => {
                  if (!isLogin) {
                    setOpen(true)
                  } else {
                    Taro.navigateTo({url: "/moduleB/pages/wallet/withdraw"})
                  }
                }}
            >
              <div><i className='icon icon-tuikuan'/></div>
              <div>退款申请</div>
            </div>
            <div
                className='card'
                onClick={() => {
                  if (!isLogin) {
                    setOpen(true)
                  } else {
                    Taro.navigateTo({url: "/moduleA/pages/order/index"})
                  }
                }}
            >
              <div><i className='icon icon-quanbudingdan'/></div>
              <div>订单记录</div>
            </div>
          </View>
        </View>
        {
          stationList.length ? <ScrollView
              scrollY
              scrollWithAnimation
              className='scrollview'
              enhanced
              onScrollEnd={(e) => {
                console.log('onScrollEnd', e);
                // scrollTop > 0, PullToRefresh 不触发 touchmove 事件。
                if (e.detail?.scrollTop) {
                  setScrollTop(e.detail?.scrollTop)
                }
              }}
          >
            <PullToRefresh
                scrollTop={scrollTop}
                onRefresh={() => {
                  dispatch({
                    type: 'stations/init',
                    payload: {
                      action
                    }
                  });
                }}
            >
              {stationList.map((i, index) => {
                return (
                    <View
                        onClick={() => {
                          if (i.stationId && i.pileIds){
                            dispatch({
                              type: 'stations/goStationDetail',
                              payload: {
                                current: {
                                  ...i
                                }
                              }
                            })
                          } else {
                            Taro.showToast({
                              title: '数据丢失',
                              icon: 'error'
                            })
                          }
                        }}
                        id={index === stationList.length - 1 ? `stationListId${i.stationId}` : ''}
                    >
                      <StationCard station={i} />
                    </View>
                )
              })}
            </PullToRefresh>
            {loading ? <View className='tooltip'>
              <ConfigProvider theme={{ nutuiLoadingIconSize: '20px' }}>
                <Loading type='spinner' >更多数据加载中... </Loading>
              </ConfigProvider>
            </View> : pageSize >= total ? <View className='tooltip'>-已经到底了-</View> : <View className='tooltip'>-上滑加载更多-</View>}
            <BackTop />
          </ScrollView> :  <Empty description={loading ? '数据加载中...' : '站列表空空如也~~' } style={{backgroundColor: 'transparent', paddingTop: '300rpx'}} />
        }
        <AtModal
            isOpened={activityVisible}
            footer={null}
            closeOnClickOverlay={false}
            // closeIcon
            // closeIconPosition='bottom'
            onClose={() => setActivityVisible(false)}
            className='activeWrap'
        >
          <AtModalHeader>
            {/*<View style={{fontWeight: 'bold'}}>*/}
            {/*  <div className='activeTitle'>活动上新,优惠不停</div>*/}
            {/*  <div className='activeSubTitle'>{allActivities.length ? allActivities[swiperCurrent]?.activityName : ''}</div>*/}
            {/*  <div className='activeTime'>*/}
            {/*    {allActivities.length ?*/}
            {/*        `活动时间: ${moment(allActivities[swiperCurrent]?.activityStartTime).format('MM月DD日')}-${moment(allActivities[swiperCurrent]?.activityEndTime).format('MM月DD日')}`*/}
            {/*        : ''*/}
            {/*    }*/}
            {/*  </div>*/}
            {/*</View>*/}
            <View className='top-images'>
              {/*<Image src='https://jgy-1313248182.cos.ap-nanjing.myqcloud.com/active.gif' mode='widthFix' width='172px'></Image>*/}
              {/*<Image src='http://obs-jgy.nyjinguan.com/jgy/images/20241203082256.gif' mode='widthFix' width='172px'></Image>*/}
              <Image src='https://jgdq.obs.cn-southwest-2.myhuaweicloud.com/jgy/images/20241203082256.gif' mode='widthFix' width='172px'></Image>
            </View>
          </AtModalHeader>
          <AtModalContent className='couponWrap'>
            <ScrollView style={{maxHeight: '500rpx', minHeight: '280rpx'}} scrollY>
              {
                // allActivities.length ?
                //     <Swiper
                //         indicatorColor='#999'
                //         indicatorActiveColor='#ff6619'
                //         circular
                //         indicatorDots={allActivities.length > 1}
                //         current={swiperCurrent}
                //         onChange={(val) => {
                //           setSwiperCurrent(val.detail.current)
                //         }}
                //     >
                //       {
                //         allActivities.map((l) => <SwiperItem>
                //           {
                //             allCouponsAvailable.length ? [...allCouponsAvailable].map((i) => (
                //                 <View className='couponItem'>
                //                   <div className='couponLeftTag'>{i.couponObject === 1 ? '服务费' : '电费'}</div>
                //                   <div className='couponCardItem'>
                //                     <div className='couponLeft'>
                //                       {
                //                         i.couponType ===1 ? <div style={{whiteSpace: 'nowrap'}}><span className='value'>¥{i.couponAmount || ''}</span></div>
                //                             : <div style={{whiteSpace: 'nowrap'}}><span className='value'>{i.couponAmount || ''}折</span></div>
                //                       }
                //                       <div className='desc'>
                //                         {`${i.conditionsAstrict ? i.conditionsAstrict === 1 ? `电费满${i.astrictAmount || ''}元可用` : `充电量满${i.astrictAmount || '' }度可用` : '无门槛'}` }
                //                       </div>
                //                     </div>
                //                     <div className='couponLine' />
                //                     <div className='couponCenter'>
                //                       <div className='name'>{i.couponName}</div>
                //                       <div className='validityTime'>{i.couponValidityType === 1 ? `${i.validityTime || ''}到期` : `领取后${i.validityTime || ''}天内可用`}</div>
                //                     </div>
                //                     {
                //                       i.drawDown === 1 ?
                //                           <div className='rightTag' style={{backgroundColor: 'transparent'}}> <Tag type='warning'>已领取</Tag></div> :   <div
                //                               className='right'
                //                               onClick={() => {
                //                                 dispatch({
                //                                   type: 'stations/attendActivity',
                //                                   payload: {
                //                                     activityId: l.activityId,
                //                                     activityType: l.activityType,
                //                                     couponId: i.couponId,
                //                                   }
                //                                 })
                //                               }}
                //                           >领取</div>
                //                     }
                //                   </div>
                //                 </View>
                //             )) : null
                //           }
                //         </SwiperItem>)
                //       }
                //     </Swiper> : null
                allCouponsAvailable.length ? [...allCouponsAvailable].map((i) => (
                    <View className='couponItem'>
                      <div className='couponLeftTag'>{i.couponObject === 1 ? '服务费' : '电费'}</div>
                      <div className='couponCardItem'>
                        <div className='couponLeft'>
                          {
                            i.couponType ===1 ? <div style={{whiteSpace: 'nowrap'}}><span className='value'>¥{i.couponAmount || ''}</span></div>
                                : <div style={{whiteSpace: 'nowrap'}}><span className='value'>{i.couponAmount || ''}折</span></div>
                          }
                          <div className='desc'>
                            {`${i.conditionsAstrict ? i.conditionsAstrict === 1 ? `电费满${i.astrictAmount || ''}元可用` : `充电量满${i.astrictAmount || '' }度可用` : '无门槛'}` }
                          </div>
                        </div>
                        <div className='couponLine' />
                        <div className='couponCenter'>
                          <div className='name'>{i.couponName}</div>
                          <div className='validityTime'>{i.couponValidityType === 1 ? `${i.validityTime || ''}到期` : `领取后${i.validityTime || ''}天内可用`}</div>
                        </div>
                        {
                          i.drawDown === 1 ?
                              <div className='rightTag' style={{backgroundColor: 'transparent'}}> <Tag type='warning'>已领取</Tag></div> :   <div
                                  className='right'
                                  onClick={() => {
                                    dispatch({
                                      type: 'stations/attendActivity',
                                      payload: {
                                        activityId: i.activityId,
                                        activityType: i.activityType,
                                        couponId: i.couponId,
                                      }
                                    })
                                  }}
                              >领取</div>
                        }
                      </div>
                    </View>
                )) : null
              }
            </ScrollView>
          </AtModalContent>
          <AtModalAction>
            <View className='couponFooter' onClick={() => setActivityVisible(false)}>关闭</View>
          </AtModalAction>
        </AtModal>
        {!!allActivities.length && isLogin && !activityVisible ? <View onClick={() => setActivityVisible(true)} className='fixBtn'>领券</View> : null}
        <AtModal isOpened={isOpened}>
          <AtModalHeader>温馨提示</AtModalHeader>
          <AtModalContent>
            <View className='modalContent'>
              请先登录再进行操作
            </View>
          </AtModalContent>
          <AtModalAction>
            <View className='modalFooter'>
              <AtButton
                  plain
                  style={{border: 'none'}}
                  onClick={() => setOpen(false)}
              >取消</AtButton>
              <AtButton
                  plain
                  style={{border: 'none'}}
                  openType='getPhoneNumber'
                  onGetPhoneNumber={(e) => {
                    const accessToken = Taro.getStorageSync('access_token')
                    const {detail: {iv, encryptedData} = {}} = e;
                    if (encryptedData && iv) {
                      // wxLogin();
                      setOpen(false);
                      setTimeout(() => {
                        const session_key = Taro.getStorageSync('session_key') || '';
                        const openid = Taro.getStorageSync('openid') || '';
                        if (openid && session_key) {
                          Taro.request({
                            url: `${base}/wxLogin`,
                            data: {
                              encryptedData,
                              iv,
                              openid,
                              sessionKey: session_key
                            },
                            header: {
                              "content-type": "application/json",
                              "appid": 'wx52f6aba688ce70f6',
                              "Authorization": accessToken ? "Bearer " + accessToken : '',
                            },
                            method: "POST",
                          }).then((res) => {
                            const {data: {code, data: {
                              phoneNumber: phone, token
                            } = {}} = {}} = res;
                            console.log('wxLogin', res);
                            if (code === 200) {
                              Taro.showToast({
                                title: '登录成功',
                                icon: 'success'
                                // duration: 2000
                              })
                              Taro.setStorageSync('isLogin', true);
                              Taro.setStorageSync('access_token', token);
                              Taro.setStorageSync('phoneNumber', phone);
                              // dispatch({
                              //   type: 'app/upState',
                              //   payload: {
                              //     phoneNumberInStore: phoneNumber
                              //   }
                              // })
                              dispatch({
                                type: 'wallet/getBalance'
                              });
                              dispatch({
                                type: 'stations/getChargingOrderInfo'
                              });
                              Taro.reLaunch({
                                url: '/pages/index/index'
                              })
                            } else {
                              Taro.showToast({
                                title: '登录失败,请重试',
                                icon: 'none'
                                // duration: 2000
                              })
                            }
                          });
                        }
                      }, 100)
                    }
                  }}
              >确定</AtButton>
            </View>
          </AtModalAction>
        </AtModal>
      </View>
  )
}

function mapStateToProps({
                           app = {},
                           stations: {
                             stationList = [],
                             allActivities = [],
                             myCoupons = [],
                             searchValue = '',
                             pageNum = 1,
                             pageSize = 10,
                             total = 0,
                           } = {},
                           loading: {effects: {"stations/load": loading = false} = {}} = {},
                         }) {
  return {
    ...app,
    stationList,
    allActivities,
    myCoupons,
    searchValue,
    pageNum,
    pageSize,
    total,
    loading,
  };
}

export default connect(mapStateToProps)(Index);
